package com.example.auth.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CustomUserDetailsService  implements UserDetailsService {
    private Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);
    @Autowired
    private  IUserService userService;
    @Autowired
    private IMenuService menuService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.example.auth.entity.User  user = userService.findByUserName(username);
         Long uid =  user.getId();
         List<String> authes =menuService.findAuthoritiesByUid(uid);
        if (Objects.isNull(user)){
            throw new RuntimeException("用户名或密码错误");
        }else {
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            // 向集合中添加SimpleGrantedAuthority实例
            // SimpleGrantedAuthority是GrantedAuthority的一个简单实现
            for (String s:authes){
                authorities.add(new SimpleGrantedAuthority(s));
            }
            logger.info("authorities:{}",authorities);

            return new User(username,new BCryptPasswordEncoder().encode(user.getPassword()), authorities);
        }

    }
}
